package com.example.demoapp.ui;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.example.demoapp.R;
import com.example.domain.entity.Post;

public class PostAdapter extends ListAdapter<Post, PostAdapter.PostViewHolder> {
    protected PostAdapter() {
        super(DIFF_CALLBACK);
    }

    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new PostViewHolder(LayoutInflater.from(parent.getContext())
                .inflate(R.layout.view_post_list_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
        holder.title.setText(getItem(position).getTitle());
        holder.content.setText(getItem(position).getBody());
    }


    public static class PostViewHolder extends RecyclerView.ViewHolder {

        private TextView title;
        private TextView content;

        public PostViewHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
            content = itemView.findViewById(R.id.content);
        }
    }

    public static final DiffUtil.ItemCallback<Post> DIFF_CALLBACK =
            new DiffUtil.ItemCallback<Post>() {
                @Override
                public boolean areItemsTheSame(
                        @NonNull Post oldPost, @NonNull Post newPost) {
                    return oldPost.getId() == newPost.getId();
                }

                @Override
                public boolean areContentsTheSame(
                        @NonNull Post oldPost, @NonNull Post newPost) {
                    return oldPost.equals(newPost);
                }
            };
}
